package com.arvin.faceDetect.utils

import android.graphics.Bitmap
import android.util.LruCache

/**
 * Bitmap对象池
 * 用于复用Bitmap对象，减少内存分配和GC
 */
object BitmapPool {
    private const val MAX_POOL_SIZE = 10
    private val pool = LruCache<String, Bitmap>(MAX_POOL_SIZE)

    /**
     * 获取指定大小的Bitmap
     * 如果池中有可复用的Bitmap，则复用；否则创建新的
     */
    fun getBitmap(width: Int, height: Int): Bitmap {
        val key = "${width}x${height}"
        var bitmap = pool.get(key)

        if (bitmap == null || bitmap.isRecycled) {
            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
            pool.put(key, bitmap)
        }

        return bitmap.copy(Bitmap.Config.ARGB_8888, true)
    }

    /**
     * 回收Bitmap到对象池
     */
    fun recycleBitmap(bitmap: Bitmap) {
        if (!bitmap.isRecycled) {
            val key = "${bitmap.width}x${bitmap.height}"
            pool.put(key, bitmap)
        }
    }

    /**
     * 清空对象池
     */
    fun clear() {
        pool.evictAll()
    }
} 